package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.DmcCsunButtonLocationMapper;
import com.csun.cmny.provider.exceptions.DmcBizException;
import com.csun.cmny.provider.model.domain.DmcCsunButtonLocation;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.domain.DmcDeviceAlert;
import com.csun.cmny.provider.model.dto.button.BindCsunButtonLocationDto;
import com.csun.cmny.provider.model.dto.button.CsunButtonPageQuery;
import com.csun.cmny.provider.model.dto.csunbutton.BedOldmanCsunButtonReqDto;
import com.csun.cmny.provider.model.dto.propertyManagement.SelectDeviceDataDto;
import com.csun.cmny.provider.model.enums.button.DmcCsunButtonBindTypeEnum;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.vo.CsunButtonReqVo;
import com.csun.cmny.provider.model.vo.OldmanBedRoomBuildingVo;
import com.csun.cmny.provider.model.vo.RoomBuildingVo;
import com.csun.cmny.provider.model.vo.csunbutton.DmcCsunButtonVo;
import com.csun.cmny.provider.model.vo.propertyManagement.PropertyDataVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.DmcCsunButtonLocationService;
import com.csun.cmny.provider.service.DmcDeviceAlertService;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.csun.cmny.provider.service.OmcRpcService;
import com.csun.cmny.util.PubUtils;
import com.csun.cmny.util.PublicUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-02-11 20:05
 * @Description: the class dmc csun button location service
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DmcCsunButtonLocationServiceImpl extends BaseService<DmcCsunButtonLocation>
        implements DmcCsunButtonLocationService {

    @Resource
    private OmcRpcService omcRpcService;

    @Resource
    private DmcDeviceService dmcDeviceService;

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private DmcCsunButtonLocationMapper dmcCsunButtonLocationMapper;

    @Resource
    private DmcDeviceAlertService dmcDeviceAlertService;

    /**
     * bind csun button location
     *
     * @param bindCsunButtonLocationDto bind csun button location dto
     * @return the int.
     */
    @Override
    public Integer bindCsunButtonLocation(BindCsunButtonLocationDto bindCsunButtonLocationDto,
                                          LoginAuthDto loginAuthDto) {

        // 1.校验智能床垫 - 日创
        DmcDevice dmcDevice = dmcDeviceService
                .checkDeviceIsCsunButtonByDeviceId(bindCsunButtonLocationDto.getDeviceId());
        if (PublicUtil.isEmpty(dmcDevice)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610030, bindCsunButtonLocationDto.getDeviceId());
        }

        // 2.校验紧急按钮是否已经被绑定
        DmcCsunButtonLocation dmcCsunButtonLocationQuery = dmcCsunButtonLocationMapper
                .selectByPrimaryKey(bindCsunButtonLocationDto.getDeviceId());
        if (PublicUtil.isNotEmpty(dmcCsunButtonLocationQuery)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610031, dmcCsunButtonLocationQuery.getDeviceId(),
                    dmcCsunButtonLocationQuery.getLocation());
        }

        // TODO 按钮绑定老人、床位的关系 1:1:1

        // 3.校验绑定类型
        Preconditions.checkArgument(!PubUtils.isNull(bindCsunButtonLocationDto.getBindType()),
                cmnyMessageSource.getMessage("csun.button.location.bind.type.null", null));

        Preconditions.checkArgument(bindCsunButtonLocationDto.getBindType() >= 0
                        && bindCsunButtonLocationDto.getBindType() <= 2,
                cmnyMessageSource.getMessage("csun.button.location.bind.type.range", null));

        // 4.校验位置
        if (bindCsunButtonLocationDto.getBindType().equals(DmcCsunButtonBindTypeEnum.CUSTOM.getKey())) {
            Preconditions.checkArgument(!PubUtils.isNull(bindCsunButtonLocationDto.getLocation()),
                    cmnyMessageSource.getMessage("csun.button.location.null", null));
        }

        if (bindCsunButtonLocationDto.getBindType().equals(DmcCsunButtonBindTypeEnum.OLDMAN.getKey())) {
            // 校验老人Id和老人姓名
            Preconditions.checkArgument(!PubUtils.isNull(bindCsunButtonLocationDto.getOldmanId()),
                    cmnyMessageSource.getMessage("csun.button.location.oldman.id.null", null));

            Preconditions.checkArgument(!PubUtils.isNull(bindCsunButtonLocationDto.getOldmanName()),
                    cmnyMessageSource.getMessage("csun.button.location.oldman.name.null", null));
            // TODO 校验老人Id是否存在
            OldmanBedRoomBuildingVo oldmanBedRoomBuildingVo = omcRpcService
                    .queryOldmanBedRoomBuildingByOldmanId(bindCsunButtonLocationDto.getOldmanId());
            if (PublicUtil.isEmpty(oldmanBedRoomBuildingVo)) {
                // 老人不存在
                throw new DmcBizException(ErrorCodeEnum.DMC100610062);
            }

            /**
             * @date    2019-05-22
             * @author  chisj
             * @desc    校验老人是否已经绑定过紧急按钮
             */
//            dmcCsunButtonLocationQuery = new DmcCsunButtonLocation();
//            dmcCsunButtonLocationQuery.setBindType(DmcCsunButtonBindTypeEnum.OLDMAN.getKey());
//            dmcCsunButtonLocationQuery.setOldmanId(bindCsunButtonLocationDto.getOldmanId());
//            int count = dmcCsunButtonLocationMapper.selectCount(dmcCsunButtonLocationQuery);
//            if (count > 0) {
//                // 老人已经绑定过紧急按钮
//                throw new DmcBizException(ErrorCodeEnum.DMC100610064);
//            }
//
            bindCsunButtonLocationDto.setOldmanName(oldmanBedRoomBuildingVo.getOldmanName());
            if (PublicUtil.isNotEmpty(oldmanBedRoomBuildingVo.getBedId())) {
                bindCsunButtonLocationDto.setBedId(oldmanBedRoomBuildingVo.getBedId());
                bindCsunButtonLocationDto.setLocation(oldmanBedRoomBuildingVo.getLocation());
            }

            /**
             * @date    2019-11-18
             * @author  chisj
             * @desc    老人可以进行一对多绑定紧急按钮
             */
        }

        // 5.校验床位Id
        if (bindCsunButtonLocationDto.getBindType().equals(DmcCsunButtonBindTypeEnum.BED.getKey())) {
            // 绑定类型为房间
            Preconditions.checkArgument(!PubUtils.isNull(bindCsunButtonLocationDto.getBedId()),
                    cmnyMessageSource.getMessage("csun.button.location.bed.id.null", null));
            // 校验床位Id是否存在
            // TODO 校验床位Id是否存在
            OldmanBedRoomBuildingVo bedRoomBuildingVo = omcRpcService
                    .queryOldmanBedRoomBuildingByBedId(bindCsunButtonLocationDto.getBedId());
            if (PublicUtil.isEmpty(bedRoomBuildingVo)) {
                // 床位不存在
                throw new DmcBizException(ErrorCodeEnum.DMC100610060);
            }

            /**
             * @date    2019-05-22
             * @author  chisj
             * @desc    校验床位是否绑定过紧急按钮
             */
//            dmcCsunButtonLocationQuery = new DmcCsunButtonLocation();
//            dmcCsunButtonLocationQuery.setBindType(DmcCsunButtonBindTypeEnum.BED.getKey());
//            dmcCsunButtonLocationQuery.setBedId(bindCsunButtonLocationDto.getBedId());
//            int count = dmcCsunButtonLocationMapper.selectCount(dmcCsunButtonLocationQuery);
//            if (count > 0) {
//                // 老人已经绑定过紧急按钮
//                throw new DmcBizException(ErrorCodeEnum.DMC100610065);
//            }
//
//            bindCsunButtonLocationDto.setOldmanId(bedRoomBuildingVo.getOldmanId());
//            bindCsunButtonLocationDto.setOldmanName(bedRoomBuildingVo.getOldmanName());
//            bindCsunButtonLocationDto.setLocation(bedRoomBuildingVo.getLocation());
            /**
             * @date    2019-11-18
             * @author  chisj
             * @desc    床位可以进行一对多绑定紧急按钮
             */
        }

        // 6.添加绑定
        DmcCsunButtonLocation dmcCsunButtonLocation = new DmcCsunButtonLocation();
        BeanUtils.copyProperties(bindCsunButtonLocationDto, dmcCsunButtonLocation);
        dmcCsunButtonLocation.setUpdateInfo(loginAuthDto);

        return dmcCsunButtonLocationMapper.insertSelective(dmcCsunButtonLocation);
    }

    /**
     * break csun button location
     *
     * @param deviceId device id
     * @return the int.
     */
    @Override
    public Integer breakCsunButtonLocation(Long deviceId) {

        // 1.判断设备Id是否存在
        DmcDevice dmcDevice = dmcDeviceService.checkDeviceIsCsunButtonByDeviceId(deviceId);
        if (PublicUtil.isEmpty(dmcDevice)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610030, deviceId);
        }

        // 2.判断紧急按钮是否已经绑定
        DmcCsunButtonLocation dmcCsunButtonLocationQuery = dmcCsunButtonLocationMapper
                .selectByPrimaryKey(deviceId);
        if (PublicUtil.isEmpty(dmcCsunButtonLocationQuery)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610032, deviceId);
        }

        // 3.解绑紧急按钮
        Integer result = dmcCsunButtonLocationMapper.deleteByPrimaryKey(deviceId);
        if (result > 0) {
            dmcDeviceAlertService.deleteByDeviceId(deviceId);
        }

        return result;
    }



    /**
     * query csun button list with page
     *
     * @param csunButtonPageQuery csun button page query
     *
     * @return the page info.
     */
    @Override
    public PageInfo queryGroupCsunButtonListWithPage(CsunButtonPageQuery csunButtonPageQuery) {

        PageHelper.startPage(csunButtonPageQuery.getPageNum(), csunButtonPageQuery.getPageSize());

        List<DmcCsunButtonVo> dmcCsunButtonVoList = dmcCsunButtonLocationMapper
                .queryGroupCsunButtonListWithPage(csunButtonPageQuery);

        return new PageInfo<>(dmcCsunButtonVoList);
    }

    /**
     * get csun button by device id
     *
     * @param deviceId device id
     * @return dmc csun button vo
     */
    @Override
    public DmcCsunButtonVo getCsunButtonByDeviceId(Long deviceId) {

        CsunButtonPageQuery csunButtonPageQuery = new CsunButtonPageQuery();
        csunButtonPageQuery.setDeviceId(deviceId);
        csunButtonPageQuery.setDeviceType(DmcDeviceTypeEnum.CSUN_BUTTON.getIndex());

        PageHelper.startPage(1, 1);

        List<DmcCsunButtonVo> dmcCsunButtonVoList = dmcCsunButtonLocationMapper
                .queryGroupCsunButtonListWithPage(csunButtonPageQuery);

        if (PubUtils.isNull(dmcCsunButtonVoList)) {
            return null;
        }

        return dmcCsunButtonVoList.get(0);
    }

    /**
     * get csun button by device id
     *
     * @param deviceNo device no
     * @return dmc csun button vo
     */
    @Override
    public DmcCsunButtonVo getCsunButtonByDeviceNo(String deviceNo) {

        CsunButtonPageQuery csunButtonPageQuery = new CsunButtonPageQuery();
        csunButtonPageQuery.setDeviceNo(deviceNo);
        csunButtonPageQuery.setDeviceType(DmcDeviceTypeEnum.CSUN_BUTTON.getIndex());

        PageHelper.startPage(1, 1);

        List<DmcCsunButtonVo> dmcCsunButtonVoList = dmcCsunButtonLocationMapper
                .queryGroupCsunButtonListWithPage(csunButtonPageQuery);

        if (PubUtils.isNull(dmcCsunButtonVoList)) {
            return null;
        }

        return dmcCsunButtonVoList.get(0);
    }

    /**
     * get csun button by oldman id
     *
     * @param oldmanId oldman id
     * @return dmc csun button vo
     */
    @Override
    public DmcCsunButtonVo getCsunButtonByOldmanId(Integer oldmanId) {

        CsunButtonPageQuery csunButtonPageQuery = new CsunButtonPageQuery();
        csunButtonPageQuery.setOldmanId(oldmanId);
        csunButtonPageQuery.setDeviceType(DmcDeviceTypeEnum.CSUN_BUTTON.getIndex());

        PageHelper.startPage(1, 1);

        List<DmcCsunButtonVo> dmcCsunButtonVoList = dmcCsunButtonLocationMapper
                .queryGroupCsunButtonListWithPage(csunButtonPageQuery);

        if (PubUtils.isNull(dmcCsunButtonVoList)) {
            return null;
        }

        return dmcCsunButtonVoList.get(0);
    }

    /**
     * delete csun button by id
     *
     * @param id id
     * @return the int
     */
    @Override
    public Integer deleteCsunButtonById(Long id) {

        // 1.判断设备Id是否存在
        DmcDevice dmcDevice = dmcDeviceService.checkDeviceIsCsunButtonByDeviceId(id);
        if (PublicUtil.isEmpty(dmcDevice)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100610030, id);
        }

        // 2.判断紧急按钮是否已经绑定
        DmcCsunButtonLocation dmcCsunButtonLocationQuery = dmcCsunButtonLocationMapper
                .selectByPrimaryKey(id);
        if (PublicUtil.isNotEmpty(dmcCsunButtonLocationQuery)) {
            dmcCsunButtonLocationMapper.deleteByPrimaryKey(id);
        }

        // 3.删除设备
        return dmcDeviceService.deleteDmcDeviceById(id);
    }

    @Override
    public Map<String, Object> getRecentData(Integer oldmanId) {
        return dmcCsunButtonLocationMapper.getRecentData(oldmanId);
    }
    /**
     * query csun button by bed oldman list
     *
     * @param bedOldmanCsunButtonReqDtoList bed oldman csun button req dto list
     *
     * @return the lis.
     */
    @Override
    public List<CsunButtonReqVo> queryCsunButtonByBedOldmanList(List<BedOldmanCsunButtonReqDto> bedOldmanCsunButtonReqDtoList) {
        return dmcCsunButtonLocationMapper.queryCsunButtonByBedOldmanList(bedOldmanCsunButtonReqDtoList);
    }

    @Override
    public List<PropertyDataVo> selectDeviceData(SelectDeviceDataDto selectDeviceDataDto) {
        return dmcCsunButtonLocationMapper.selectDeviceData(selectDeviceDataDto);
    }
    //查询该设备报警时间间隔
    @Override
    public DmcCsunButtonVo queryGroupCsunButton(CsunButtonPageQuery csunButtonPageQuery) {
        return dmcCsunButtonLocationMapper.queryGroupCsunButton(csunButtonPageQuery);
    }
    /**
     * 添加紧急按钮报警时间
     */
    @Override
    public Integer updateAlarmTime(DmcCsunButtonLocation dmcCsunButton) {
        return dmcCsunButtonLocationMapper.updateAlarmTime(dmcCsunButton);
    }


}
